package com.xinjian.jianba.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xinjian.jianba.dao.dwmart.CallProcedureDao;
import com.xinjian.jianba.dao.dwmid.ProductDao;
import com.xinjian.jianba.dao.dwmid.UserAccountDetailDao;
import com.xinjian.jianba.enity.ProductEnity;
import com.xinjian.jianba.enity.UserAccountDetailEnity;
import com.xinjian.jianba.service.ProcedureService;
import com.xinjian.jianba.utils.Constants;
import com.xinjian.jianba.utils.DateUtil;
import com.xinjian.jianba.utils.JsonUtil;
import com.xinjian.jianba.utils.ListUtil;

@Service
public class ProcedureServiceImpl implements ProcedureService {

	private static final Logger LOGGER = LoggerFactory.getLogger(ProcedureServiceImpl.class);

	@Autowired
	private CallProcedureDao callProcedureDao;

	@Autowired
	public UserAccountDetailDao userAccountDetailDao;

	@Autowired
	private ProductDao productDao;

	// list数据分隔大小
	public static Integer CUT_LIST_SIZE = 500;

	/**
	 * 计算数据
	 *
	 */
	@Override
	public void calMeetMatch() {
		Map<String, Object> calMeetMatchMap = new HashMap<String, Object>();
		String result = null;
		calMeetMatchMap.put("i_cal_time", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		calMeetMatchMap.put("o_outflag", result);

		callProcedureDao.calMeetMatch(calMeetMatchMap);

		LOGGER.info("--------calMeetMatchMap--------" + calMeetMatchMap.get("o_outflag"));

	}

	/**
	 * 清理临时数据
	 *
	 */
	@Override
	public void delMeetData() {

		Map<String, Object> delMeetDataMap = new HashMap<String, Object>();
		String delResult = null;
		delMeetDataMap.put("i_cal_time", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		delMeetDataMap.put("o_outflag", delResult);

		callProcedureDao.delMeetData(delMeetDataMap);

		LOGGER.info("--------delMeetDataMap----------" + delMeetDataMap.get("o_outflag"));

	}

	/**
	 * 首次登陆时
	 *
	 */
	@Override
	public void calFirstMeet(Long userId) {
		Map<String, Object> calFirstMeetMap = new HashMap<String, Object>();
		String delResult = null;
		calFirstMeetMap.put("i_user_id", userId);
		calFirstMeetMap.put("i_cal_time", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		calFirstMeetMap.put("o_outflag", delResult);

		callProcedureDao.calFirstMeet(calFirstMeetMap);

		LOGGER.info("--------delMeetDataMap----------" + calFirstMeetMap.get("o_outflag"));

	}

	/**
	 * 随机生成,当擦肩，共度，同行匹配不到人时调用
	 */
	@Override
	public void IND_MEET_MATCH(Long userId) {
		Map<String, Object> calIndMeetMap = new HashMap<String, Object>();
		String delResult = null;
		calIndMeetMap.put("i_user_id", userId);
		calIndMeetMap.put("i_cal_time", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		calIndMeetMap.put("o_outflag", delResult);
		callProcedureDao.IND_MEET_MATCH(calIndMeetMap);
		LOGGER.info("--------calIndMeetMap----------" + calIndMeetMap.get("o_outflag"));

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer orderPeriod(Integer orderPeriod) {
		List<UserAccountDetailEnity> accountDetailList = userAccountDetailDao.selectOrderPeriodStatus(orderPeriod);
		if (CollectionUtils.isNotEmpty(accountDetailList) && accountDetailList.size() > 0) {
			List<Long> productIdList = new ArrayList<Long>();
			Set<Long> productIdSet = new HashSet<Long>();
			accountDetailList.parallelStream().forEach(enity -> {
				productIdList.add(enity.getProductId());
				productIdSet.add(enity.getProductId());

			});

			Map<Long, Integer> IdQtyMap = productIdList.stream() // list 对应的 Stream
					.collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b));

			LOGGER.info("--------IdQtyMap----------" + JsonUtil.getJsonString(IdQtyMap));

			if (CollectionUtils.isNotEmpty(productIdList) && productIdList.size() > 0) {
				//批量处理商品
				List<List<Long>> listLists = ListUtil.splitList(new ArrayList<>(productIdSet), Constants.CUT_LIST_SIZE);
				for (List<Long> idList : listLists) {
					List<ProductEnity> productEnityList = this.productDao.findByIdList(idList);
					if (CollectionUtils.isNotEmpty(productEnityList)) {
						List<ProductEnity> productList = new ArrayList<ProductEnity>();
						productEnityList.parallelStream().forEach(enity -> {
							ProductEnity productEnity = new ProductEnity();
							productEnity.setId(enity.getId());
							int sellQty = enity.getSellQty() - IdQtyMap.get(enity.getId());
							if (sellQty < 0) {
								sellQty = 0;
							}
							productEnity.setSellQty(sellQty);
							productEnity.setQty(enity.getQty() + IdQtyMap.get(enity.getId()));
							productEnity.setValueVersion(enity.getValueVersion());
							productList.add(productEnity);
						});
						int line = this.productDao.updateBatchQty(productList);
						LOGGER.info("--------this.productDao.updateBatchQty----------" + line);

					}
				}
			}
		}
		return userAccountDetailDao.updateOrderPeriodStatus(orderPeriod);
	}
}
